const { doRequest } = require("../utils/request_tool");
const { BaseCommand } = require("./base");
const crypto = require("node:crypto");
const { getCache, setCache } = require("../utils/cache_tool");

class TranslateCommand extends BaseCommand {
    async execute() {
        const data = this.selfData;
        const q = this.content;
        const from = data.from || "auto";
        const to = data.to || "zh";
        const appid = "20181030000227685";
        const secret = "Clf6hhkAfZuXsNewanRf";
        const salt = "tsubasa";
        const sign = crypto
            .createHash("md5")
            .update(`${appid}${q}${salt}${secret}`)
            .digest("hex");
        const cache = (await getCache("translate")) || {};
        const ret = cache[from]?.[to]?.[q];
        if (ret) {
            return ret;
        }
        const translatedRaw = await doRequest({
            src: "https://fanyi-api.baidu.com/api/trans/vip/translate",
            quiet: true,
            options: {
                method: "POST",
                formData: {
                    q,
                    from,
                    to,
                    appid,
                    salt,
                    sign,
                },
            },
        });
        try {
            const translatedData = JSON.parse(translatedRaw);
            const ret = translatedData?.trans_result?.[0]?.dst;
            if (ret) {
                cache[from] || (cache[from] = {});
                cache[from][to] || (cache[from][to] = {});
                cache[from][to][q] = ret;
                setCache("translate", cache);
            }
            return ret || "";
        } catch (_error) {
            return "";
        }
    }

    getRequireContent() {
        return true;
    }
}

module.exports = {
    TranslateCommand,
};
